import { LcDocument } from '@/types/modules/editor/types/editor.type';
import { ITypeEntity } from '@/types/modules/superType/types/type/superType.type';

/**
 * 路径配置中心 - 统一管理所有目录路径
 */
export const PATH_CONFIG = {
  // 根目录
  ROOT: '/',
  SRC: '/src',
  // 主要目录
  PAGES: '/src/pages',
  COMPONENTS: '/src/components',
  MODULES: '/src/modules',
  TYPES: '/src/types',
  DOCS: '/docs', // 文档放在根目录
  UTILS: '/src/utils',
  APIS: '/src/apis',
  STORE: '/src/store',
  CLOUD_FUNCTIONS: '/src/cloud_functions',
  DATABASE: '/src/database',
  CONFIG: '/src/config',
  // 根目录常见文件
  PACKAGE_JSON: '/package.json',
  README: '/README.md',
  GITIGNORE: '/.gitignore',
  TSCONFIG: '/tsconfig.json',
} as const;

export const defaultPathMap = {
  cloud_function: PATH_CONFIG.CLOUD_FUNCTIONS,
  action: PATH_CONFIG.UTILS,
  api: PATH_CONFIG.APIS,
  vo: PATH_CONFIG.TYPES,
  code: PATH_CONFIG.DOCS,
  flow: PATH_CONFIG.DOCS,
  typescript: PATH_CONFIG.SRC,
  javascript: PATH_CONFIG.SRC,
  text: PATH_CONFIG.DOCS,
  sql: PATH_CONFIG.DATABASE,
  json: PATH_CONFIG.CONFIG,
};

export function getDocumentPath(doc: LcDocument | Partial<LcDocument>): string {
  const { type, fileName } = doc;
  let { folder } = doc;
  if (!folder) {
    folder = PATH_CONFIG.PAGES;
  }
  if (folder) {
    switch (type) {
      case 'Page':
        // 页面使用小写驼峰命名
        return `${folder}/${fileName}.doc`;
      case 'Component':
        // 组件使用大写驼峰命名
        return `${folder}/${fileName}.doc`;
      case 'Block':
        return `${folder}/${fileName}.doc`;
      default:
        return `${folder}/${fileName}.doc`;
    }
  }

  return `${folder}/${fileName}.doc`;
}

export const typePathCache = new Map<string, string>();

export function getTypePath(type: ITypeEntity, category?: string): string {
  const key = type._id + category;
  if (typePathCache.has(key)) {
    return typePathCache.get(key);
  }
  const path = getTypePathNoCache(type, category);
  typePathCache.set(key, path);
  if (path === '/src/pages/.json') {
    console.warn('/src/pages/.json type: ', type);
    // debugger;
    // throw new Error('fuck');
  }
  if (path === '/src/pages/data.data') {
    console.warn('/src/pages/data.data type: ', type);
    // debugger;
    // throw new Error('fuck');
  }
  return path;
}

/**
 * 获取类型实体的路径
 */
export function getTypePathNoCache(
  type: ITypeEntity,
  category?: string,
): string {
  const extMap: Record<ITypeEntity['type'], string> = {
    cloud_function: 'node.ts',
    folder: 'folder',
    vo: 'm.ts',
    constants: 'store.ts',
    props: 'props',
    db: 'db',
    dto: 'dto',
    action: 'util.ts',
    query: 'query',
    api: 'api.ts',
    'api-import': 'apidoc.json',
    config: 'config',
    scene: 'scene',
    'cloud-app': 'cloud-app',
    code: 'code',
    data: 'data',
    draw: 'draw',
    flow: 'flow',
    typescript: 'ts',
    javascript: 'js',
    text: 'txt',
    sql: 'sql',
    json: 'json',
  };
  if (type.type === 'folder') {
    return type.folderPath + '/';
  }

  let name = type.name;
  let desc = type.desc;
  if (type.type === 'cloud_function' && name) {
    // 云函数：路径转换为文件名，如 user/api/get-info -> user|api|get-info
    name = name.startsWith('/')
      ? name.substring(1).replaceAll('/', '|')
      : name.replaceAll('/', '|');
  } else if (type.type === 'api' && type.uri) {
    // API 文档：路径和方法转换为文件名，如 POST /article/list -> ArticleListPost
    const pathPart = type.uri.startsWith('/')
      ? type.uri.substring(1).replaceAll('/', '-')
      : type.uri.replaceAll('/', '-');

    // 将路径转换为驼峰命名，并添加方法后缀
    const camelCasePath = pathPart
      .split('-')
      .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
      .join('');

    const method = type.method
      ? type.method.charAt(0).toUpperCase() + type.method.slice(1).toLowerCase()
      : 'Get';
    name = `${camelCasePath}${method}`;
  }

  let extName = extMap[type.type];
  if (type.type === 'code') {
    if (type.language === 'markdown') {
      extName = 'md';
    }
    if (type.language === 'typescript') {
      extName = 'ts';
    }
    if (type.language === 'javascript') {
      extName = 'js';
    }
    if (type.language === 'text') {
      extName = 'txt';
    }
    if (type.language === 'sql') {
      extName = 'sql';
    }
    if (type.language === 'json') {
      extName = 'json';
    }
  }

  // 使用简化命名规范：直接使用 name，不添加 desc 前缀
  let virtualFileName = `${name || desc}.${extName}`;
  let defaultPath = defaultPathMap[type.type];
  if (type.type === 'code' && type.language === 'markdown') {
    defaultPath = PATH_CONFIG.DOCS;
  }
  let prefix = type.folder || category || defaultPath || type.type;
  if (!prefix?.startsWith('/')) {
    prefix = `/${prefix}`;
  }

  // 全局数据
  if (type.type === 'data' && !type.fileName) {
    if (!type.folder || type.name === 'constants') {
      return `${PATH_CONFIG.STORE}/global.store.ts`;
    }
  }
  if (type.folder) {
    if (type.type === 'cloud_function') {
      // 云函数使用管道符命名：路径转为文件名，如 /article/list -> article|list
      const fileName = type.name.startsWith('/')
        ? type.name.substring(1).replaceAll('/', '|')
        : type.name.replaceAll('/', '|');
      return `${prefix}/${fileName}.node.ts`;
    }
    return `${prefix}/${virtualFileName}`;
  }

  if (type.type === 'cloud_function') {
    // 云函数使用管道符命名：路径转为文件名，如 /article/list -> article|list
    const fileName = type.name.startsWith('/')
      ? type.name.substring(1).replaceAll('/', '|')
      : type.name.replaceAll('/', '|');
    return `${PATH_CONFIG.CLOUD_FUNCTIONS}/${fileName}.node.ts`;
  }
  return `${prefix}/${virtualFileName}`;
}
